<?php

namespace app\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
use app\controller\LoginController;
use app\controller\InstallController;
use app\common\Tool;

class Login implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        $controller = new $request->controller;
        if (is_file(base_path('config/database.php'))) {
            //检查登录
            $Admin = session('Admin');
            if (!isset($Admin)) {
                if ($controller::class != LoginController::class) {
                    return error('请先登录', route('admin.login.index'));
                }
            } else {
                if (!Tool::isRole($Admin, $request->route)) {
                    return error('权限不足');
                }
            }
        } else if ($controller::class != InstallController::class) {
            return redirect(route("admin.install.index"));
        }

        return $next($request);
    }
}
